<template>
	<view class="container">
		<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-box">
				<image style="height: 50rpx;width: 50rpx;" src="/static/images/search.png"></image>
				<input type="text" v-model="keyword" placeholder="搜索足环号、鸽主或地址" class="search-input"
					@input="handleSearch" confirm-type="search" @confirm="handleSearch" />
				<text class="clear-btn" v-if="keyword" @tap="clearSearch">✕</text>
			</view>
		</view>

		<!-- 搜索历史 -->
		<view class="history-section" v-if="!keyword && searchHistory.length > 0">
			<view class="section-header">
				<text class="title">搜索历史</text>
				<text class="clear-history" @tap="clearHistory">清除</text>
			</view>
			<view class="history-tags">
				<text class="history-tag" v-for="(item, index) in searchHistory" :key="index"
					@tap="useHistoryKeyword(item)">{{ item }}</text>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-wrapper" v-if="loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">搜索中...</text>
		</view>

		<!-- 搜索结果 -->
		<view class="result-section" v-else-if="keyword">
			<view class="result-header" v-if="searchResults.length > 0">
				<text class="result-count">找到 {{ searchResults.length }} 条结果</text>
			</view>

			<view class="no-result" v-if="searchResults.length === 0">
				<image class="no-result-image" src="/static/no-result.png"></image>
				<text class="no-result-text">未找到相关结果</text>
			</view>

			<scroll-view scroll-y="true" class="result-list" >
				<view class="result-item" v-for="(item, index) in searchResults" :key="item._id">
					<view class="item-header">
						<text class="owner">{{ item.owner }}</text>
						<text class="rank">#{{ index + 1 }}</text>
					</view>
					<view class="info-row">
						<text class="label">上期名次：</text>
						<text class="value highred">{{ item.rank || '未排名' }}</text>
					</view>
					<view class="item-body">
						<view class="info-row">
							<text class="label">足环号：</text>
							<text class="value highlight">{{ item.foot_ring_number }}</text>
						</view>
						<view class="info-row">
							<text class="label">地址：</text>
							<text class="value">{{ item.address }}</text>
						</view>
						<view class="info-row">
							<text class="label">飞速：</text>
							<text class="value">{{ item.speed }}</text>
						<button class="add-btn" style="margin-top: -10rpx;" @tap="addToTempHistory(item)">添加</button>
						</view>
						<view class="item-header">
							
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
	<view class="tabpanel">
		<tabpanel :addData="tempHistory"></tabpanel>
	</view>
	
</template>
<script>
	const MAX_HISTORY = 10
	import Tabpanel from '@/components/Tabpanel.vue'


	export default {
		components: {
			Tabpanel
		},
		data() {
			return {
				// 搜索相关
				keyword: '',
				loading: false,
				searchResults: [],
				searchHistory: [],
				debounceTimer: null,

				// 历史记录相关
				tempHistory: [],

				// 组合相关
				relatedItems: [],

			};
		},
		onLoad() {
			// 加载搜索历史
			const history = uni.getStorageSync('searchHistory')
			if (history) {
				this.searchHistory = JSON.parse(history)
			}
		},
		methods: {
			
			handleConfirm() {
				console.log('当前关联列表数据：', this.relatedItems.parent1);
				uni.showToast({
					title: `已记录${this.relatedItems.length}条关联数据`,
					icon: 'none',
					duration: 2000
				});
			},
			async handleSearch() {
				if (!this.keyword.trim()) {
					this.searchResults = []
					return
				}

				// 防抖处理
				if (this.debounceTimer) clearTimeout(this.debounceTimer)
				this.debounceTimer = setTimeout(async () => {
					this.loading = true
					try {
						const res = await uniCloud.callFunction({
							name: 'search',
							data: {
								keyword: this.keyword.trim()
							}
						})

						if (res.result.code === 0) {
							this.searchResults = res.result.data
							this.saveToHistory(this.keyword.trim())
						} else {
							throw new Error(res.result.msg)
						}
					} catch (e) {
						uni.showToast({
							title: '搜索失败',
							icon: 'none'
						})
					} finally {
						this.loading = false
					}
				}, 300)
			},
			clearSearch() {
				this.keyword = ''
				this.searchResults = []
			},
			useHistoryKeyword(keyword) {
				this.keyword = keyword
				this.handleSearch()
			},
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '确定要清除搜索历史吗？',
					success: (res) => {
						if (res.confirm) {
							this.searchHistory = []
							uni.removeStorageSync('searchHistory')
						}
					}
				})
			},
			saveToHistory(keyword) {
				if (!keyword) return

				const index = this.searchHistory.indexOf(keyword)
				if (index > -1) {
					this.searchHistory.splice(index, 1)
				}
				this.searchHistory.unshift(keyword)

				if (this.searchHistory.length > MAX_HISTORY) {
					this.searchHistory = this.searchHistory.slice(0, MAX_HISTORY)
				}

				uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory))
			},
			addToTempHistory(item) {
				this.tempHistory = this.tempHistory || [];

				// 限制历史记录数量
				if (this.tempHistory.length >= 10) {
					this.tempHistory.pop();
				}

				// 避免重复添加
				const isDuplicate = this.tempHistory.some(
					i => i.foot_ring_number === item.foot_ring_number && i.owner === item.owner
				);

				if (!isDuplicate) {
					this.tempHistory.unshift({
						...item,
						timestamp: Date.now()
					});
					this.$forceUpdate();
					uni.showToast({
						title: '已添加到临时历史记录',
						icon: 'success',
						duration: 1000
					});
				} else {
					uni.showToast({
						title: '该记录已存在',
						icon: 'none',
						duration: 1000
					});
				}
			},
		},
	}
</script>

<style>
	.btn-container {
		display: flex;
		justify-content: space-around;
		margin: 20rpx 0;
	}
	.generate-btn {
		flex: 1;
		margin: 0 20rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		background: linear-gradient(to right, #014ed2, #43bdff);
		color: white;
		font-size: 32rpx;
		transition: all 0.3s;
	}
	.confirm-btn {
		flex: 1;
		margin: 0 20rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		background: linear-gradient(to right, #4CAF50, #8BC34A);
		color: white;
		font-size: 32rpx;
		transition: all 0.3s;
	}
	.add-btn {
		margin: 10 20rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 9rpx;
		background: linear-gradient(to right, #4CAF50, #8BC34A);
		color: white;
		font-size: 32rpx;
		transition: all 0.3s;
	}
	.btn-hover {
		opacity: 0.8;
		transform: scale(0.98);
	}
	.container {
		/* min-height: 100vh; */
		background-color: #f8fafc;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.search-section {
		background: linear-gradient(to right, #014ed2, #43bdff);
		padding: 30rpx 30rpx calc(30rpx + env(safe-area-inset-top));
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #ffffff;
		border-radius: 50rpx;
		padding: 20rpx 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		height: 40rpx;
	}

	.icon-search {
		font-size: 36rpx;
		color: #6366f1;
		margin-right: 20rpx;
	}

	.search-input {
		flex: 1;
		font-size: 32rpx;
		color: #1e293b;
	}

	.clear-btn {
		padding: 10rpx;
		color: #94a3b8;
		font-size: 32rpx;
	}

	.history-section {
		padding: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 28rpx;
		color: #64748b;
		font-weight: 500;
	}

	.clear-history {
		font-size: 24rpx;
		color: #94a3b8;
		padding: 10rpx;
	}

	.history-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.history-tag {
		padding: 12rpx 24rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: #4f46e5;
		border: 2rpx solid #e0e7ff;
	}

	.loading-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #e0e7ff;
		border-top-color: #6366f1;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #64748b;
	}

	.result-section {
		padding: 30rpx;
	}

	.result-header {
		margin-bottom: 20rpx;
	}

	.result-count {
		font-size: 24rpx;
		color: #64748b;
	}

	.no-result {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;
	}

	.no-result-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.no-result-text {
		font-size: 28rpx;
		color: #94a3b8;
	}

	.result-list {
		max-height: calc(100vh - 400rpx);
	}

	.result-item {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 10rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
		border: 2rpx solid #00aa00;
		background-image: url(/static/images/dove.png);
		background-repeat: no-repeat;
		background-position: center;
		background-size: 60%;
		background-blend-mode: overlay;
		opacity: 0.9;
		position: relative;
		overflow: hidden;
	}
	
	.result-item::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-image: url(/static/images/鸽子背景.png);
		background-repeat: no-repeat;
		background-position: 90% 90%;
		background-size: 40%;
		opacity: 0.1;
		pointer-events: none;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.owner {
		font-size: 32rpx;
		color: #1e293b;
		font-weight: 600;
	}

	.rank {
		font-size: 24rpx;
		color: #6366f1;
		background-color: #e0e7ff;
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
	}

	.info-row {
		display: flex;
		margin-bottom: 0rpx;

	}

	.info-row:last-child {
		margin-bottom: 0;
	}

	.label {
		width: 140rpx;
		font-size: 26rpx;
		color: #64748b;
	}

	.value {
		flex: 1;
		font-size: 26rpx;
		color: #334155;
	}

	.highlight {
		color: #6366f1;
		font-weight: 500;
	}

	.highred {
		color: #fc0107;
		font-weight: 500;
		font-weight: bold;
	}

</style>